 import { Notification, MessageBox, Message, Loading } from 'element-ui'
 import ms from 'element-ui/src/locale/lang/ms'
 import store from '@/store'
let CHAT = {
  SOCKET  : null ,
  SERVER_ADDR: "ws://" + window.location.hostname+":8080/smart-socket/websocket",
  NICK_NAME : '',
  CHAT_ROOM_ID : '',
  messageList:[],
  WINDOW: null
} ;


/**
 * 初始化 Websocket
 * 两个参数
 * 昵称账号
 * 所选房间号
 */
CHAT.init = function(nickName,chatRoomId,messageList,obj) {

  if (!nickName || nickName == "undefined" || nickName == "null" ||
    !chatRoomId || chatRoomId == "undefined" || chatRoomId == "null") {

    Message({ message: "聊天出现异常，原因为昵称为空或未选择房间号！", type: 'error', duration: 5 * 1000 })

    Promise.reject('聊天出现异常，原因为昵称为空或未选择房间号' )

    return ;
  }

  // 保存全局参数
  CHAT.NICK_NAME = nickName ;
  CHAT.CHAT_ROOM_ID = chatRoomId ;
  CHAT.messageList = messageList ;
  CHAT.WINDOW = obj ;

 let downloadLoadingInstance = Loading.service({ text: "正在连接服务器，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })


  try {

    if(window.WebSocket){

      // 先从状态机中获取
      let target = null ;
      if(store.getters && store.getters.ws ){
          target =  store.getters.ws ;
      }

     if(target && target !=null && target !='undefined'){
       CHAT.SOCKET = target[CHAT.NICK_NAME] ;
       }else {

       CHAT.SOCKET = new WebSocket(CHAT.SERVER_ADDR+"?"+"nickName="+nickName +"&chatRoomId="+chatRoomId ) ;

       // 保存 socket 状态
       let ws = {};

       ws[CHAT.NICK_NAME]= CHAT.SOCKET ;

       store.dispatch('app/SetWs', ws) ;

       console.log(CHAT.SERVER_ADDR+"?"+"nickName="+nickName +"&chatRoomId="+chatRoomId ,'服务器连接地址') ;
     }


      CHAT.SOCKET.onopen = function() {
        Message.info({ message: "恭喜您与服务器连接成功，您使用的房间号为【"+ chatRoomId +']', type: 'success', duration: 5 * 1000 }) ;

        let messageDTO = {
          from: '系统消息',
          to: '全员',
          content: nickName + '上线了',
          msgType: '30',
          channel: 'SYS_CHANNEL',
          sendTime : CHAT.formatDate(new Date())
        }

        CHAT.send(JSON.stringify(messageDTO)) ;

      }

      CHAT.SOCKET.onmessage = function(event ) {

        CHAT.acceptMsg(event.data) ;
      }

      CHAT.SOCKET.onclose = function() {

        if(CHAT.SOCKET == null ){
          return ;
        }

        let messageDTO = {
          from: '系统消息',
          to: '全员',
          content: nickName + '下线了',
          msgType: '30',
          channel: 'SYS_CHANNEL',
          sendTime : CHAT.formatDate(new Date())
        }

        CHAT.send(JSON.stringify(messageDTO)) ;


      }

      CHAT.SOCKET.onerror = function(err ) {

        Message({ message: "WebSocket 服务器异常，原因为："+err, type: 'error', duration: 5 * 1000 })

        downloadLoadingInstance.close() ;
      }

      downloadLoadingInstance.close() ;

    }else {

      Message({ message: "浏览器不支持 WebSocket,请更换Chrome或者FireFox", type: 'error', duration: 5 * 1000 })
      downloadLoadingInstance.close() ;
    }

  }catch (e) {
    downloadLoadingInstance.close() ;
    Message({ message: "与服务器建立连接异常，原因为"+ e, type: 'error', duration: 5 * 1000 })

  }



}


CHAT.send = function(msg) {


  if( CHAT.SOCKET == null ){

     MessageBox.confirm('您与服务器连接建立失败', '系统提示', { confirmButtonText: '请重新进入聊天室', cancelButtonText: '取消', type: 'warning' })
      .then(() => {
        window.location.href = '/connect'
      });

     return ;
  }

  if(!window.WebSocket){
    Message.error("当前浏览器不支持WebSocket ！")
    return ;
  }

  if(CHAT.SOCKET.readyState === WebSocket.OPEN){

    CHAT.SOCKET.send(msg) ;
  }else {
    Message.error("当前用户【"+CHAT.NICK_NAME +"】尚未跟 服务器建立连接，请先连接服务器，再聊天！")
    MessageBox.confirm('连接建立失败', '系统提示', { confirmButtonText: '重新进入聊天室', cancelButtonText: '取消', type: 'warning' })
      .then(() => {
        window.location.href = '/connect'
    });

  }


}

CHAT.sendMsg = function(to,messageList,textarea) {
  if (!textarea) return;

    let messageDTO = {
      from: CHAT.NICK_NAME,
      to: to,
      content: textarea,
      msgType: '10',
      channel: CHAT.CHAT_ROOM_ID,
      sendTime : CHAT.formatDate(new Date())
    }
    // 在这决定用哪个 messageList
    CHAT.messageList = null ;
    CHAT.messageList = messageList ;
    if(to && to !== 'ALL'){
      CHAT.messageList.push(messageDTO);
    }

    // 将消息发出去
    CHAT.send(JSON.stringify(messageDTO)) ;

    this.scrollToBottom();


}


/**
 * 接收别人发的消息
 */
CHAT.acceptMsg = function( msg ){

    let message = msg ;

    if(message !=null || message !='undefined'){

      let messageDTO = {} ;

      messageDTO = JSON.parse(message)

      // 忽略自己发的消息
      if(CHAT.CHAT_ROOM_ID === messageDTO.channel){
        CHAT.messageList.push({
          from: messageDTO.from,
          to: messageDTO.to,
          content: messageDTO.content,
          msgType: messageDTO.msgType,
          channel: messageDTO.channel,
          sendTime : messageDTO.sendTime
        });

        this.textarea = "";
        // 消息聊天框，滚动到最底部
        CHAT.scrollToBottom();
      }
    }
}

/**
 * 滚动窗口
 * @param obj
 */
CHAT.scrollToBottom =function() {
  setTimeout(function() {
   CHAT.WINDOW.scrollTop = CHAT.WINDOW.scrollHeight
  },0)

}


CHAT.formatDate = function(date) {

  /* 时间格式化 */

    const d = new Date(date);
    let month = "" + (d.getMonth() + 1);
    let day = "" + d.getDate();
    let hour = "" + d.getHours();
    let minute = "" + d.getMinutes();
    let second = "" + d.getSeconds();
    let year = d.getFullYear();

    if (month.length < 2) month = "0" + month;
    if (day.length < 2) day = "0" + day;
    if (hour.length < 2) hour = "0" + hour;
    if (minute.length < 2) minute = "0" + minute;
    if (second.length < 2) second = "0" + second;

    return (
      [year, month, day].join("-") + " " + [hour, minute, second].join(":")
    );

}


export default CHAT ;
